<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form divClass" v-if="headerShow" style="margin-top: 15px">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item field="value2" label="客户名称">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading3"
                                    @search="handleSearch3" v-model="pageData.kehumingcheng" :filter-option="false"
                                    allow-clear allow-search @focus="focusSel3">
                                    <a-option v-for="item in pageData.kehumingchenglist" :value="item">{{ item }}</a-option>
                                </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.kehumingcheng"
                @press-enter="huiche"
              />
            </a-form-item>

            <a-form-item field="value3" label="坯布编号">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading"
                                    @search="handleSearch1" v-model="pageData.pibubianhao" :filter-option="false"
                                    allow-clear allow-search @focus="focusSel1">
                                    <a-option v-for="item in pageData.pibubianhaolist" :value="item">{{ item }}</a-option>
                                </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.pibubianhao"
                @press-enter="huiche"
              />
            </a-form-item>

            <a-form-item field="value1" label="坯布名称">
              <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading2"
                                    @search="handleSearch2" v-model="pageData.pibumingcheng" :filter-option="false"
                                    allow-clear allow-search @focus="focusSel2">
                                    <a-option v-for="item in pageData.pibumingchenglist" :value="item">{{ item }}</a-option>
                                </a-select> -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.pibumingcheng"
                @press-enter="huiche"
              />
            </a-form-item>

            <a-form-item field="value2" label="仓库名称">
              <!-- <a-cascader class="bacClass" :style="{ width: '200px' }"  v-model="pageData.yuanliaomingcheng" :options="pageData.yuanliaomingchenglist" @focus="focusSel6"
                             @change="changeFrim"  allow-clear  />  -->
              <a-input
                allow-clear
                :style="{ width: '200px' }"
                class="bacClass"
                placeholder=""
                v-model="pageData.yuanliaomingcheng"
                @press-enter="huiche"
              />
            </a-form-item>

            <a-form-item field="value1" label="月份">
              <!-- <a-date-picker  popup-container="html"  :style="{ width: '200px' }" @press-enter="huiche" class="bacClass"
                                    v-model="pageData.jianyanriqi" /> -->
              <a-month-picker
                :style="{ width: '200px' }"
                class="bacClass"
                v-model="pageData.jianyanriqi"
                @press-enter="huiche"
              />
            </a-form-item>
          </a-form>
        </div>
      </div>
      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up
            v-if="headerShow"
            @click="headerShow = false"
            :strokeWidth="2"
            :size="18"
          />
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
        </a-divider>
      </div>
      <div class="my-tool-bar">
        <Toolbar
          class="gesture"
          :items="pageData.btnList"
          @select="selectHandler"
          @export="exports"
          @exportAll="exportAll"
          @fhzy="fhzy"
        >
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <!--
                            表格插件
                        -->
      <a-spin
        :loading="pageData.pageLoading"
        tip="加载中"
        dot
        style="height: 100%; width: 100%; z-index: 999"
      >
        <AgGridVuesCopys :rowHeight="33" :headerHeight="33"
          rowSelection="multiple"
          @grid-ready="gridReady"
          style="height: 100%"
          :defaultColDef="defaultColDef"
          :suppressCopyRowsToClipboard="true"
          class="ag-theme-alpine"
          :rowData="table.dataList"
          :columnDefs="tc"
          :localeText="localeText1"
        ></AgGridVuesCopys>
      </a-spin>
    </template>
    <paginationCopys
      :page-size-options="pagingList1"
      :total="total"
      show-total
      show-jumper
      show-page-size
      @change="PageSize"
      @page-size-change="change1"
      style="justify-content: center"
    />
    <a-drawer
      style="z-index: 999"
      ok-text="保存"
      cancel-text="关闭"
      :drawer-style="{ zIndex: 9999 }"
      :mask-closable="false"
      :width="400"
      :ok-loading="pageData.pageLoading"
      :visible="pageData.showAdd"
      unmountOnClose
      @ok="sideOk"
      @cancel="pageData.showAdd = false"
    >
      <template #title>
        {{ pageData.sideTitle }}
      </template>
      <div>
        <a-form ref="formRef" layout="horizontal" :model="dataForm">
          <a-form-item
            label-col-flex="80px"
            label="编号"
            field="brandCode"
            :rules="[{ validator: isChiese }, { required: true, message: '编号必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input
              class="bacClass"
              placeholder=""
              v-model="dataForm.brandCode"
              @blur="inputBlur"
            />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="品牌名称"
            field="brandName"
            :rules="[{ required: true, message: '品牌名称必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-input class="bacClass" placeholder="" v-model="dataForm.brandName" />
          </a-form-item>
          <a-form-item
            label-col-flex="80px"
            label="布类类型"
            field="clothClass"
            :rules="[{ required: true, message: '布类类型必填' }]"
            :validate-trigger="['change', 'blur']"
          >
            <a-select popup-container="html" 
              class="bacClass"
              :loading="loading"
              placeholder=""
              @search="handleSearch1"
              v-model="dataForm.clothClass"
              :filter-option="false"
              allow-search
              allow-clear
              @focus="focusSel1"
            >
              <a-option v-for="item in pageData.typeList" :value="item">{{ item }}</a-option>
            </a-select>
          </a-form-item>
          <a-form-item label-col-flex="80px" label="备注" field="remark">
            <!-- <a-input v-model="dataForm.remark" /> -->
            <a-textarea
              class="bacClass"
              v-model="dataForm.remark"
              :max-length="400"
              allow-clear
              show-word-limit
            />
          </a-form-item>
        </a-form>
      </div>
    </a-drawer>
  </pageTabelLayout>
</template>

<script lang="ts">
import { post, get } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table'
import emitter from '@/hooks/useEventBus'
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue'
import { Button, Form, Message, Modal } from '@arco-design/web-vue'
import { FormInstance } from '@arco-design/web-vue/es/form'
import { baseURL } from '../../../api/axios.config'
import axios from 'axios'
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue'
import MyTable from '@/components/MyTable'
import ButtonRenderer from '@/components/TableCellRenderer/ButtonRenderer'
import { template } from 'lodash'
import { setupGlobalComponent } from '@/layouts'
import { localeText } from '@/api/aggridZw'
// 引入

import { stringify } from 'qs'
import { pagingList } from '@/api/paging'
import { slicing } from '@/utils/caseFrimAndSecRig'
interface BrandInfo {
  id: any
  brandCode: string
  brandName: string
  clothClass: string
  remark: string
  deleteState: number | string
  createName: string
  createTime: string
  updateName: string
  updateTime: string
}

export default {
  name: 'SecondaryGreymonth',

  setup(props: any, { emit }) {
    const total = ref(0)
    const page = ref(1)
    const size = ref(10)
    function PageSize(val: any) {
      page.value = val
      doRefresh()
    }
    function change1(val: any) {
      size.value = val
      doRefresh()
    }
    const headerShow = ref<boolean>(true)

    function doRefresh() {
      //localStorage.setItem("yyyyy","8888888")
      var obj = { page: page.value, size: size.value }
      if (pageData.kehumingcheng != '') {
        obj['client'] = pageData.kehumingcheng
      }
      if (pageData.zhizaocode != '') {
        obj['weavingSerialNumber'] = pageData.zhizaocode
      }
      if (pageData.pibubianhao != '') {
        obj['greigeCode'] = pageData.pibubianhao
      }
      if (pageData.pibumingcheng != '') {
        obj[' greigeName'] = pageData.pibumingcheng
      }
      if (pageData.jitaihao != '') {
        obj['machine'] = pageData.jitaihao
      }
      if (pageData.jianyanriqi != '') {
        obj['billDate'] = pageData.jianyanriqi
      }
      if (pageData.firmId2 != '') {
        obj['checkStaff'] = pageData.firmId2
      }
      localStorage.setItem('cnmw', JSON.stringify(obj))

      pageData.pageLoading = true
      post({
        url: 'product/statement/getGreyDefectiveInfo',
        data: {
          page: page.value,
          size: size.value,
          grayCode: pageData.pibubianhao,
          grayName: pageData.pibumingcheng,
          customerName: pageData.kehumingcheng,
          warehouseName: pageData.yuanliaomingcheng,
          date: pageData.jianyanriqi,
        },
      })
        .then(({ data, code }: any) => {
          if (code === 200) {
            table.handleSuccess(data.data)
            total.value = data.total
            // 查询方法改

            gridOption.value.setRowData(data.data)
            total.value = data.length
            var shangyuejiecunpishu = 0
            var shangyuejiecunzhongliang = 0
            var benyuerukupishu = 0
            var benyuerukuzhongliang = 0
            var benyuechukupishu = 0
            var benyuechukuzhongliang = 0
            var benyuejiecunpishu = 0
            var benyuejiecunzhongliang = 0
            data.data.map((o: any) => {
              shangyuejiecunpishu = shangyuejiecunpishu + Number(o.lastNum)
              shangyuejiecunzhongliang = shangyuejiecunzhongliang + Number(o.lastWeight)
              benyuerukupishu = benyuerukupishu + Number(o.nowIntoNum)
              benyuerukuzhongliang = benyuerukuzhongliang + Number(o.nowIntoWeight)
              benyuechukupishu = benyuechukupishu + Number(o.nowOutNum)
              benyuechukuzhongliang = benyuechukuzhongliang + Number(o.nowOutWeight)
              benyuejiecunpishu = benyuejiecunpishu + Number(o.nowNum)
              benyuejiecunzhongliang = benyuejiecunzhongliang + Number(o.nowWeight)
            })
            var newRows = [
              {
                workshop: '',
                warehouseName: '',
                warehouseCode: '',
                customerName: '',
                grayCode: '',
                grayName: '',
                grayBatch: '',
                machineCode: '',
                level: '',
                lastNum: shangyuejiecunpishu,
                lastWeight: shangyuejiecunzhongliang,
                nowIntoNum: benyuerukupishu,
                nowIntoWeight: benyuerukuzhongliang,
                nowOutNum: benyuechukupishu,
                nowOutWeight: benyuechukuzhongliang,
                nowNum: benyuejiecunpishu,
                nowWeight: benyuejiecunzhongliang,
              },
            ]
            gridOption.value.setPinnedBottomRowData(newRows)
            pageData.hejishuzu = newRows as any
          }
        })
        .catch(console.log)
        .finally(() => {
          pageData.pageLoading = false
        })
    }

    const { selectedRowKeys, onSelectionChange } = useRowSelection()
    const pagination = usePagination(doRefresh)
    const table = useTable()
    const rowKey = useRowKey('id')
    const tableColumns = useTableColumn([
      {
        title: '公司',
        key: 'workshop',
        dataIndex: 'workshop',
        width: 150,
      },

      {
        title: '仓库编号',
        key: 'warehouseCode',
        dataIndex: 'warehouseCode',
        width: 150,
      },
      {
        title: '仓库名称',
        key: 'warehouseName',
        dataIndex: 'warehouseName',
        width: 150,
      },
      {
        title: '客户名称',
        key: 'customName',
        dataIndex: 'customName',
        width: 150,
      },
      {
        title: '坯布编号',
        key: 'grayCode',
        dataIndex: 'greyCode',
        width: 200,
      },
      {
        title: '坯布名称',
        key: 'grayName',
        dataIndex: 'greyName',
        width: 150,
      },

      {
        title: '颜色',
        key: 'colorName',
        dataIndex: 'colorName',
        width: 200,
      },

      {
        title: '上月结存匹数',
        key: 'lastNum',
        dataIndex: 'lastNum',
        width: 200,
      },
      {
        title: '上月结存重量',
        key: 'lastWeight',
        dataIndex: 'lastWeight',
        width: 200,
      },
      {
        title: '本月入库匹数',
        key: 'nowIntoNum',
        dataIndex: 'nowIntoNum',
        width: 200,
      },
      {
        title: '本月入库重量',
        key: 'nowIntoWeight',
        dataIndex: 'nowIntoWeight',
        width: 200,
      },
      {
        title: '本月出库匹数',
        key: 'nowOutNum',
        dataIndex: 'nowOutNum',
        width: 200,
      },
      {
        title: '本月出库重量',
        key: 'nowOutWeight',
        dataIndex: 'nowOutWeight',
        width: 200,
      },
      {
        title: '本月结存匹数',
        key: 'nowNum',
        dataIndex: 'nowNum',
        width: 200,
      },
      {
        title: '本月结存重量',
        key: 'nowWeight',
        dataIndex: 'nowWeight',
        width: 200,
      },
    ])

    let tc: any[] = tableColumns.map((o) => {
      let obj = {
        headerName: o.title,
        field: o.key,
        pinned: o['fixed'],
        tooltipField: o.key,
      }
      if (o.slotName === 'act') {
        obj['resizable'] = false
        obj['filter'] = false
        obj['sortable'] = false
        obj['lockPosition'] = 'right'

        obj['cellRenderer'] = {
          template: `<a-tag color="#ff7d00" class="gesture" v-if="e" @click="a">修改</a-tag>`,
          setup(props: any) {
            const a = () => {
              editHandler(props.params.data)
            }
            return {
              e: pageData.isEdit,
              a,
            }
          },
        }
      }

      return obj
    })

    let a = [
      {
        showRowGroup: 'hide_def',
        headerName: '',
        checkboxSelection: true,
        headerCheckboxSelection: true,
        pinned: 'left',
        width: 50,
        resizable: false,
        filter: false,
        sortable: false,
        minWidth: 50,
        maxWidth: 50,
        lockPosition: 'left',
      },
    ]
    tc = a.concat(tc)
    const pageData = reactive<{
      showAdd: boolean
      sideTitle: string
      dropDownData: any
      nameList: []
      pageLoading: boolean
      typeList: []
      dropDownData1: any
      rHeight: any
      btnList: any[]
      isEdit: boolean
      zhizaocode: any
      hejishuzu: []
      pibubianhao: any
      pibubianhaolist: []
      pibumingcheng: any
      pibumingchenglist: []
      kehumingcheng: any
      kehumingchenglist: any[]
      jianyanriqi: any
      jitaihao: any
      jitaihaolist: []
      firmId2: any
      firmList2: []
      yuangongName: []
      yuanliaomingcheng: any
      yuanliaomingchenglist: any[]
      biaoji: any
    }>({
      nameList: [],
      showAdd: false,
      sideTitle: '新增品牌资料',
      dropDownData: '',
      pageLoading: false,
      typeList: [],
      dropDownData1: '',
      rHeight: 0,
      btnList: [],
      isEdit: false,
      zhizaocode: '',
      hejishuzu: [],
      pibubianhao: '',
      pibubianhaolist: [],
      pibumingcheng: '',
      pibumingchenglist: [],
      kehumingcheng: '',
      kehumingchenglist: [] as any,
      jianyanriqi: '',
      jitaihao: '',
      jitaihaolist: [],
      firmId2: '',
      firmList2: [],
      yuangongName: [],
      yuanliaomingcheng: '',
      yuanliaomingchenglist: [] as any,
      biaoji: 0,
    })

    interface gcType {
      id: any
      company: any
    }

    //下拉框得到焦点
    const focusSel = () => {
      selCxAll({ brandName: '', deleteState: 0 })
    }
    //下拉数据

    onMounted(() => {
      // 切换tap到本页面执行的方法
      emitter.on('BrandInfo', () => {
        // selCxAll1({});
        doRefresh()
      })
    })
    let cxbl = ''
    //查询
    const selectHandler = () => {
      pagination.page = 1
      cxbl = pageData.dropDownData
      doRefresh()
    }
    const queryData = reactive({
      clothType: '',
    })
    const addHandler = () => {}
    const dataForm = reactive<BrandInfo>({
      id: null,
      remark: '',
      brandName: '',
      clothClass: '',
      deleteState: '',
      createName: '',
      createTime: '',
      updateName: '',
      updateTime: '',
      brandCode: '',
    })

    // 表格准备事件
    const gridOption = ref()
    const gridReady = (params: any) => {
      gridOption.value = params.api
    }

    let formRef = ref<FormInstance>()
    const sideOk = () => {
      formRef.value?.validate().then((err) => {
        if (!err) {
          formRef.value?.validate().then((err) => {
            if (!err) {
              pageData.pageLoading = true
              if (pageData.sideTitle === '新增品牌资料') {
                post({
                  url: 'product/Brand/insert',
                  data: [dataForm],
                })
                  .then((res: any) => {
                    if (res.code === 200) {
                      formRef.value?.resetFields()
                      pageData.showAdd = false

                      Message.success({
                        content: '新增成功',
                        duration: 5000,
                      })
                    } else {
                      Message.error({
                        content: res.message,
                        duration: 5000,
                      })
                    }
                    doRefresh()
                  })
                  .finally(() => {
                    doRefresh()
                    pageData.pageLoading = false
                  })
              } else {
                post({
                  url: 'product/Brand/update',
                  data: [dataForm],
                })
                  .then((res: any) => {
                    if (res.code === 200) {
                      formRef.value?.resetFields()
                      pageData.showAdd = false
                      Message.success({
                        content: '修改成功',
                        duration: 5000,
                      })
                    } else {
                      Message.error({
                        content: res.message,
                        duration: 5000,
                      })
                    }
                  })
                  .finally(() => {
                    doRefresh()
                    pageData.pageLoading = false
                  })
              }
            }
          })
        }
      })
    }
    const deleteHandler = () => {
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      }

      Modal.confirm({
        title: '系统提示',
        content: '确认删除选中的数据?',
        onOk() {
          pageData.pageLoading = true
          post({
            url: 'product/Brand/deleteList',
            data: gridOption.value.getSelectedRows().map((o: any) => {
              return o.id
            }),
          })
            .then(({ code, data }: any) => {
              if (code === 200) {
                Message.success({
                  content: '删除成功',
                  duration: 5000,
                })
                pagination.page = 1
                doRefresh()
              } else {
                Message.error({
                  content: '删除失败',
                  duration: 5000,
                })
              }
            })
            .finally(() => {
              pageData.pageLoading = false
            })
        },
      })
    }

    let curobj = null
    const editHandler = (record: BrandInfo) => {
      curobj = record
      selCxAll({ key: '' })
      dataForm.brandCode = record.brandCode
      dataForm.brandName = record.brandName
      dataForm.clothClass = record.clothClass
      dataForm.remark = record.remark
      dataForm.id = record.id
      pageData.sideTitle = '修改品牌资料'
      pageData.showAdd = true
    }
    //判断是否填写了中文
    const isChiese = (value: string, cb: Function) => {
      return new Promise<void>((resolve) => {
        if (window.encodeURI(value).indexOf('%') !== -1) {
          cb('填写的值不能包含中文！')
        }
        resolve()
      })
    }
    //input离开焦点 将小写转大写
    const inputBlur = () => {
      dataForm.brandCode = dataForm.brandCode.toUpperCase()
    }
    //导出
    const exports = () => {
      //
      var zongshuzu = [] as any
      gridOption.value.getSelectedRows().forEach(function (o: any) {
        zongshuzu.push(o)
      })
      pageData.hejishuzu.forEach((o: any) => {
        zongshuzu.push(o)
      })
      localStorage.setItem('daocu', JSON.stringify(zongshuzu))
      //
      if (gridOption.value.getSelectedRows().length === 0) {
        Message.error('请先勾选')
        return
      } else {
        let idList: any = []
        // gridOption.value.getSelectedRows().forEach(function(o:any){
        //     idList.push(o['id'])
        // })
        zongshuzu.forEach(function (o: any) {
          idList.push(o['id'])
        })

        //将表头拼接出来
        let head =
          '<th>车间</th><th>仓库编号</th><th>仓库名称</th><th>坯布编号</th><th>坯布名称</th><th>颜色</th><th>上月结存匹数</th><th>上月结存重量</th><th>本月入库匹数</th><th>本月入库重量</th>'
        head +=
          '<th>本月出库匹数</th><th>本月出库重量</th><th>本月结存匹数</th><th>本月结存重量</th>'

        //拿到当前表格数据与勾选的行做筛选

        // let nowRow = table.dataList.filter(function (o) {
        //     return (gridOption.value.getSelectedRows().map((o: any) => { return o.id })).indexOf(o["id"]) !== -1;
        // })
        let nowRow = zongshuzu.filter(function (o) {
          return (
            zongshuzu
              .map((o: any) => {
                return o.id
              })
              .indexOf(o['id']) !== -1
          )
        })
        let body = ''
        var shangyuejiecunpishu = 0
        var shangyuejiecunzhongliang = 0
        var benyuerukupishu = 0
        var benyuerukuzhongliang = 0
        var benyuechukupishu = 0
        var benyuechukuzhongliang = 0
        var benyuejiecunpishu = 0
        var benyuejiecunzhongliang = 0
        nowRow.forEach(function (o, index) {
          if (index != nowRow.length - 1) {
            shangyuejiecunpishu = shangyuejiecunpishu + o['lastNum']
            shangyuejiecunzhongliang = shangyuejiecunzhongliang + o['lastWeigh']
            benyuerukupishu = benyuerukupishu + o['nowIntoNum']
            benyuerukuzhongliang = benyuerukuzhongliang + o['nowIntoWeight']
            benyuechukupishu = benyuechukupishu + o['nowOutNum']
            benyuechukuzhongliang = benyuechukuzhongliang + o['nowOutWeight']
            benyuejiecunpishu = benyuejiecunpishu + o['nowNum']
            benyuejiecunzhongliang = benyuejiecunzhongliang + o['nowWeight']
          } else {
            o['lastNum'] = shangyuejiecunpishu
            o['lastWeigh'] = shangyuejiecunzhongliang
            o['nowIntoNum'] = benyuerukupishu
            o['nowIntoWeight'] = benyuerukuzhongliang
            o['nowOutNum'] = benyuechukupishu
            o['nowOutWeight'] = benyuechukuzhongliang
            o['nowNum'] = benyuejiecunpishu
            o['nowWeight'] = benyuejiecunzhongliang
          }

          body += '<tr><td>' + o['workshop'] + '</td>'
          body += '<td>' + o['warehouseCode'] + '</td>'
          body += '<td>' + o['warehouseName'] + '</td>'
          body += '<td>' + o['customerName'] + '</td>'
          body += '<td>' + o['grayCode'] + '</td>'

          body += '<td>' + o['grayName'] + '</td>'
          body += '<td>' + o['colorName'] + '</td>'
          body += '<td>' + o['lastNum'] + '</td>'
          body += '<td>' + o['lastWeight'] + '</td>'
          body += '<td>' + o['nowIntoNum'] + '</td>'
          body += '<td>' + o['nowIntoWeight'] + '</td>'
          body += '<td>' + o['nowOutNum'] + '</td>'
          body += '<td>' + o['nowOutWeight'] + '</td>'
          body += '<td>' + o['nowNum'] + '</td>'
          body += '<td>' + o['nowWeight'] + '</td>'

          body += '</tr>'
        })
        tableToXlsx(head, '坯布月报表', body)
        console.log(table)
      }
    }
    const exportAll = () => {
      post({
        url: '/product/statement/exportGetGreyDefectiveInfo',
        data: {
          grayCode: pageData.pibubianhao,
          grayName: pageData.pibumingcheng,
          customerName: pageData.kehumingcheng,
          warehouseName: pageData.yuanliaomingcheng,
          date: pageData.jianyanriqi,
        },
        responseType: 'blob'
      }).then((res) => {
        filedownload(res, '次布仓报表.xlsx')
      });

    }

    function tableToXlsx(head: any, filename: any, body: any) {
      const uri = 'data:application/vnd.ms-excel;base64,',
        template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`

      const a = document.createElement('a')
      a.href = uri + window.btoa(unescape(encodeURIComponent(template)))
      a.download = filename
      a.click()
      document.removeChild(a)
    }

    //模板下载
    const downloadHandler = () => {
      axios
        .get(baseURL + '/product/Brand/uploadModel', {
          responseType: 'blob',
          headers: {
            token: sessionStorage.getItem('USER-TOKEN-KEY'),
          },
        })
        .then((res) => {
          if (res.status === 200) {
            filedownload(res.data, '品牌资料.xlsx')
          }
        })
    }
    //导入
    const importHandler = () => {
      const inputEle: HTMLInputElement = document.createElement('input')
      inputEle.type = 'file'
      inputEle.id = 'fileUploadExcel'
      inputEle.accept =
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
      inputEle.addEventListener('change', (e) => {
        const formData = new FormData()
        if (inputEle.files !== null) {
          formData.append('file', inputEle.files[0] || '')
        } else {
          Message.warning('未选择文件！')
          return
        }
        pageData.pageLoading = true
        axios
          .post(baseURL + '/product/Brand/importModelData', formData, {
            headers: {
              'Content-Type': 'multipart/form-data',
              token: sessionStorage.getItem('USER-TOKEN-KEY'),
            },
          })
          .then((result) => {
            if (result.data['code'] === 200) {
              Message.success('导入成功')
            } else {
              Message.error(result.data.message)
            }
          })
          .finally(() => {
            pageData.pageLoading = false
            doRefresh()
          })
      })
      inputEle.click()
    }
    //下拉数据
    const options = ref<any>(pageData.pibubianhaolist)
    const loading = ref(false)
    const handleSearch1 = (value: any) => {
      if (value) {
        const ob = { greyCode: value }
        loading.value = true

        selCxAll(ob)
        options.value = pageData.pibubianhaolist
        loading.value = false
      } else {
        options.value = []
      }
    }

    //下拉框查询 布料类型
    //下拉框查询 坯布编号
    function selCxAll(val: any) {
      post({
        url: 'product/Rawmaterial/getGreyDrop',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.pibubianhaolist = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    const options2 = ref<any>(pageData.pibumingchenglist)
    const loading2 = ref(false)
    const handleSearch2 = (value: any) => {
      if (value) {
        const ob = { grayFabricName: value }
        loading.value = true

        selCxAll2(ob)
        options.value = pageData.pibumingchenglist
        loading.value = false
      } else {
        options.value = []
      }
    }
    //下拉框查询 坯布名称
    function selCxAll2(val: any) {
      post({
        url: 'product/Rawmaterial/getGreyDrop',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          pageData.pibumingchenglist = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    const options3 = ref<any>(pageData.kehumingchenglist)
    const loading3 = ref(false)
    const handleSearch3 = (value: any) => {
      if (value) {
        const ob = { customName: value }
        loading.value = true

        selCxAll3(ob)
        options.value = pageData.kehumingchenglist
        loading.value = false
      } else {
        options.value = []
      }
    }
    function selCxAll3(val: any) {
      post({
        url: 'planSingle/planOrder/getDropInfo',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");
          //sessionStorage.setItem("kehumingccheng",JSON.stringify(data))
          //sessionStorage.setItem("iskehupp",JSON.stringify(data))

          pageData.kehumingchenglist = data
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    const options4 = ref<any>(pageData.jitaihaolist)
    const loading4 = ref(false)
    const handleSearch4 = (value: any) => {
      if (value) {
        const ob = { machineCode: value }
        loading.value = true

        selCxAll4(ob)
        options.value = pageData.jitaihaolist
        loading.value = false
      } else {
        options.value = []
      }
    }
    //下拉框查询 坯布名称
    function selCxAll4(val: any) {
      post({
        url: 'planSingle/machine/getFieldValue',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          // (data as string[]).splice(0, 0, "全部");

          pageData.jitaihaolist = data
          //sessionStorage.setItem("kehumingccheng",JSON.stringify(pageData.jitaihao))
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    function selCxAll6(val: any) {
      pageData.biaoji = 2
      pageData.yuanliaomingchenglist = []
      post({
        url: '/wms/warehouseType/getWarehoursTypePara',
        data: val,
      }).then(({ data, code }: any) => {
        if (code === 200) {
          data.forEach((o: any) => {
            var obj = { label: o.typeName, value: o.id, children: [] }
            pageData.yuanliaomingchenglist.push(obj)
          })

          pageData.yuanliaomingchenglist.forEach((d) => {
            // gongsi(d)
          })
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }
    //下拉框得到焦点
    const focusSel1 = () => {
      selCxAll({ greyCode: '' })
    }
    const focusSel2 = () => {
      selCxAll2({ grayFabricName: '' })
    }

    const focusSel3 = () => {
      selCxAll3({ customName: '' })
    }
    const focusSel4 = () => {
      selCxAll4({ machineCode: '' })
    }

    const focusSel6 = () => {
      selCxAll6({})
    }
    //设置权限
    // ['查询', '新增', '删除', '导出', '导入']
    const permissionStore = usePermission()

    if (permissionStore.hasPermisson('ppzl.cx')) {
      pageData.btnList.push('查询')
    }

    if (permissionStore.hasPermisson('ppzl.dc')) {
      pageData.btnList.push('导出')
      pageData.btnList.push('全部导出')
    }
    if (permissionStore.hasPermisson('ppzl.dr')) {
      pageData.btnList.push('返回主页')
    }
    if (permissionStore.hasPermisson('ppzl.xg')) {
      pageData.isEdit = true
    }
    const handleChange = (_data: any) => {
      table.handleSuccess(_data)
    }
    const fhzy = () => {
      emit('takebiaoji', 0)
    }
    //获得公司部门组下的员工
    const getFirmGroup = () => {
      get({
        url: '/org/firmGroup/getTreeFirmGroup',
      }).then(({ code, data }) => {
        if (code === 200) {
          pageData.firmList2 = data
          huoquyuangong()
        }
      })
    }
    const huoquyuangong = () => {
      pageData.firmList2.forEach((o: any) => {
        o.children.forEach((d: any) => {
          d.children.forEach((a: any) => {
            post({
              url: 'org/employee/getList',
              data: {
                groupId: a.value,
                empName: '',
              },
            }).then((res) => {
              if (res.code == 200) {
                res.data.forEach((m: any) => {
                  a.children = [{ label: m.empName, value: m.empName }]
                })
              } else {
                Message.error({
                  content: '查询员工名称失败',
                  duration: 5000,
                })
              }
            })
          })
        })
      })
    }

    //获得公司
    // function gongsi(val: any) {

    //     post({
    //         url: "/org/firmGroup/getFirmInfoByMap",
    //         data: {}
    //     }).then(({ data, code }: any) => {
    //         if (code === 200) {
    //             data.map((o: any) => {
    //                 val.children.push({ label: o.firmName, value: o.id, warehouseTypeName: val.label, children: [] })

    //             })
    //             val.children.map((a: any) => {
    //                 getcangku(a);

    //             })

    //         } else {
    //             Message.error({
    //                 content: "查询失败！",
    //                 duration: 5000,
    //             });
    //         }
    //     });

    // }
    function getcangku(val: any) {
      post({
        url: '/wms/warehouse/getWarehouseByPara',
        data: { firmId: val.value, warehouseTypeName: val.warehouseTypeName,virtuallyState:0 },
      }).then(({ data, code }: any) => {
        if (code === 200) {
          data.map((d: any) => {
            val.children.push({
              label: d.warehouseName,
              value: d.id,
              firmId: d.firmId,
              warehouseTypeName: d.warehouseTypeName,
            })
          })

          val.children.map((a: any) => {
            // getyuanliaobianhao(a);
          })
        } else {
          Message.error({
            content: '查询失败！',
            duration: 5000,
          })
        }
      })
    }

    const defaultColDef = {
      sortable: true,
      resizable: true,
      filter: true,
      // flex: 1
    }
    const localeText1: any = ref(localeText)
    const huiche = () => {
      doRefresh()
    }
    const pagingList1: any = ref(pagingList)
    return {
      pagingList1,
      huiche,
      localeText1,
      defaultColDef,
      tc,
      total,
      PageSize,
      change1,
      page,
      size,
      editHandler,
      deleteHandler,
      sideOk,
      formRef,
      dataForm,
      addHandler,
      selectedRowKeys,
      pagination,
      tableColumns,
      table,
      rowKey,
      pageData,
      queryData,
      selectHandler,
      isChiese,
      inputBlur,
      exports,
      exportAll,
      options,
      options2,
      options3,
      options4,
      loading,
      loading2,
      loading3,
      loading4,
      handleSearch1,
      handleSearch2,
      handleSearch3,
      handleSearch4,
      focusSel,
      downloadHandler,
      importHandler,
      focusSel1,
      focusSel2,
      focusSel3,
      focusSel4,
      focusSel6,
      headerShow,
      handleChange,
      gridReady,
      fhzy,
      selCxAll,
      getFirmGroup,
    }
  },
  props: {
    biaoji: Number,
  },
  components: { Toolbar, PageTabelLayout,  },
}
</script>
<style scoped>
:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}
</style>
